package cn.stylefeng.guns.core.schedue.spring;

import cn.stylefeng.guns.config.redis.redis.util.Redishandler0;
import cn.stylefeng.guns.core.RecoverConst;
import cn.stylefeng.guns.core.UserGradeLevel;
import cn.stylefeng.guns.modular.business.entity.UserGrade;
import cn.stylefeng.guns.modular.business.entity.UserProperty;
import cn.stylefeng.guns.modular.business.model.dto.KeyValueDTO;
import cn.stylefeng.guns.modular.business.model.result.UserPropertyResult;
import cn.stylefeng.guns.modular.business.service.CardService;
import cn.stylefeng.guns.modular.business.service.UserGradeService;
import cn.stylefeng.guns.modular.business.service.UserPropertyService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 升级用户任务
 *
 * @Author pzp .
 * @Date 2019/8/215:05
 */
@Slf4j
@Component
public class UserGradeTask {

    @Autowired
    private CardService cardService;

    @Autowired
    private Redishandler0 redishandler0;

    @Autowired
    private UserPropertyService userPropertyService;

    @Autowired
    private UserGradeService userGradeService;

    @Async("analyzeUserGradeAsync")
    public void configureTasks(Long userId) {
        log.info("执行升级用户等级开始时间:{} ", LocalDateTime.now());
        //从缓存中获取等级分数
        Map<Object, Object> gradeMap = redishandler0.getHashMap(RecoverConst.USER_GRADE_REDIS_KEY, "");
        //获取所有用户总面值
        UserPropertyResult userPropertyResult = cardService.allUserQuota(userId);
        if (gradeMap.containsKey(userPropertyResult.getGradeLevel())){
            UserGrade grade = JSONObject.parseObject(userPropertyResult.getGradeLevel().toString(), UserGrade.class);
            if (new BigDecimal(userPropertyResult.getQuota().toString()).intValue()>=grade.getUpScore()){
                //升级用户等级
                UserProperty userProperty = new UserProperty();
                userProperty.setUpdateTime(new Date());
                userProperty.setUserId(userId);
                userProperty.setGradeLevel(userPropertyResult.getGradeLevel()+1);
                userProperty.setGradeId(userGradeService.getUserGradeByLevel(userProperty.getGradeLevel()).getGradeId());
                userPropertyService.updateById(userProperty);
            }
        }
        log.info("执行升级用户等级结束时间:{} ", LocalDateTime.now());
    }
}
